import { h } from 'vue'
import { Flex, Button, Tag, Drawer, List, Typography, Space, Spin } from 'ant-design-vue'
import { Attachments } from 'ant-design-x-vue'
import { FileTextOutlined, LinkOutlined, CalendarOutlined } from '@ant-design/icons-vue'
import MarkdownIt from 'markdown-it'
import { ref } from 'vue'

const md = new MarkdownIt()
const { Text, Paragraph } = Typography

// 知识来源抽屉状态
const sourceDrawerVisible = ref(false)
const currentSources = ref([])

// 显示知识来源
const showSources = (sources) => {
  currentSources.value = sources
  sourceDrawerVisible.value = true
}

// 角色样式配置
export const roles = {
  ai: {
    placement: 'start',
    variant: 'borderless',
    // typing: { step: 5, interval: 50 },
    loadingRender: () =>
      h('div', { class: 'flex items-center space-x-4 py-3' }, [
        // 波浪动画效果
        h('div', { class: 'flex items-end space-x-1' }, [
          h('div', {
            class: 'w-1 bg-gradient-to-t from-blue-400 to-blue-600 rounded-full',
            style: 'height: 8px; animation: wave 1.2s ease-in-out infinite; animation-delay: 0s;',
          }),
          h('div', {
            class: 'w-1 bg-gradient-to-t from-purple-400 to-purple-600 rounded-full',
            style:
              'height: 12px; animation: wave 1.2s ease-in-out infinite; animation-delay: 0.1s;',
          }),
          h('div', {
            class: 'w-1 bg-gradient-to-t from-pink-400 to-pink-600 rounded-full',
            style:
              'height: 16px; animation: wave 1.2s ease-in-out infinite; animation-delay: 0.2s;',
          }),
          h('div', {
            class: 'w-1 bg-gradient-to-t from-red-400 to-red-600 rounded-full',
            style:
              'height: 12px; animation: wave 1.2s ease-in-out infinite; animation-delay: 0.3s;',
          }),
          h('div', {
            class: 'w-1 bg-gradient-to-t from-orange-400 to-orange-600 rounded-full',
            style: 'height: 8px; animation: wave 1.2s ease-in-out infinite; animation-delay: 0.4s;',
          }),
        ]),
        // 打字机效果文字
        h('div', { class: 'flex items-center space-x-2' }, [
          h(
            'span',
            {
              class: 'text-sm font-medium text-gray-700',
            },
            'AI正在分析',
          ),
          h(
            'span',
            {
              class: 'text-sm font-medium text-blue-600 animate-pulse',
              style: 'animation-duration: 0.8s;',
            },
            '...',
          ),
        ]),
        // 旋转的大脑图标
        h(
          'div',
          {
            class: 'relative',
          },
          [
            h('div', {
              class:
                'w-5 h-5 border-2 border-transparent border-t-blue-500 border-r-purple-500 rounded-full animate-spin',
            }),
            h('div', {
              class:
                'absolute inset-0 w-3 h-3 m-auto bg-gradient-to-r from-blue-400 to-purple-500 rounded-full animate-pulse',
            }),
          ],
        ),
      ]),
    styles: {
      content: {
        borderRadius: '16px',
      },
    },
    // 添加内容渲染函数来处理 Markdown 和知识来源
    messageRender: (content) => {
      console.log('🐯 ~ content:', content)

      let thinking = ''
      let answer = ''
      let sources = []

      // 判断 content 的结构
      if (typeof content === 'string') {
        answer = content
      } else if (content && typeof content === 'object') {
        thinking = content.thinking || ''
        answer = content.answer || content.message || content.content || ''
        sources = content.sources || []
      }

      console.log('🐯 ~ thinking:', thinking)
      console.log('🐯 ~ answer:', answer)
      console.log('🐯 ~ sources:', sources)

      // 思考过程元素（类似DeepSeek样式）
      const thinkingElement = thinking ? h('div', { 
        class: 'mb-4 p-3 bg-gray-50 border-l-4 border-[#4f46e5]/50 rounded-r-lg'
      }, [
        h('div', { class: 'flex items-center mb-2' }, [
          h('div', { class: 'w-2 h-2 bg-blue-400 rounded-full animate-pulse mr-2' }),
          h('span', { class: 'text-sm font-medium text-gray-600' }, '思考过程')
        ]),
        h('div', { 
          class: 'text-sm text-gray-500 leading-relaxed whitespace-pre-line font-mono',
          style: 'font-family: "SF Mono", "Monaco", "Inconsolata", "Roboto Mono", monospace;'
        }, thinking)
      ]) : null

      // 回答内容元素
      const answerElement = answer ? h('div', {
        innerHTML: md.render(answer),
        class: 'prose mb-3',
      }) : null

      // 渲染知识来源（保持原有逻辑）
      const sourceElement = sources && sources.length > 0 ? 
        h('div', { class: 'mt-4 pt-3 border-t border-gray-200' }, [
          // 来源标题行
          h('div', { class: 'flex items-center justify-between mb-3' }, [
            h('div', { class: 'flex items-center text-sm text-gray-600' }, [
              h(
                'div',
                {
                  class:
                    'w-4 h-4 rounded-full bg-blue-100 flex items-center justify-center mr-2',
                },
                [h(FileTextOutlined, { class: 'text-xs text-blue-600' })],
              ),
              h('span', { class: 'font-medium' }, `参考来源 ${sources.length} 条`),
            ]),
            h(
              Button,
              {
                type: 'primary',
                size: 'small',
                onClick: () => showSources(sources),
                class:
                  'text-blue-600 hover:text-blue-700 hover:bg-blue-50 px-2 py-1 rounded text-xs',
              },
              () => '查看全部',
            ),
          ]),
          // 来源卡片列表
          h(
            'div',
            { class: 'space-y-2' },
            sources.map((source, index) => {
              const filename = source.metadata.filename
              const displayName =
                filename.length > 30 ? filename.slice(0, 30) + '...' : filename
              const fileInfo = getFileTypeInfo(filename)

              return h(
                'div',
                {
                  key: index,
                  class:
                    'group flex items-start p-3 bg-gray-50 hover:bg-gray-100 rounded-lg border border-gray-200 cursor-pointer transition-all duration-200',
                  onClick: () => showSources(sources),
                },
                [
                  // 文件图标
                  h(
                    'div',
                    {
                      class: `flex-shrink-0 w-10 h-10 rounded ${fileInfo.color} flex items-center justify-center mr-3 mt-0.5`,
                    },
                    [h('span', { class: `${fileInfo.icon} text-lg` })],
                  ),
                  // 文件信息
                  h('div', { class: 'flex-1 min-w-0' }, [
                    h('div', { class: 'flex items-center mb-1' }, [
                      h(
                        'span',
                        { class: 'text-sm font-medium text-gray-900 truncate mr-2' },
                        displayName,
                      ),
                      h(
                        'span',
                        {
                          class: `inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${fileInfo.color.replace('bg-', 'bg-').replace('text-', 'text-')}`,
                        },
                        fileInfo.label,
                      ),
                    ]),
                    h(
                      'div',
                      {
                        class: 'text-xs text-gray-500 line-clamp-2 leading-relaxed',
                      },
                      source.content.slice(0, 80) + (source.content.length > 80 ? '...' : ''),
                    ),
                  ]),
                  // 右侧箭头
                  h(
                    'div',
                    {
                      class:
                        'flex-shrink-0 ml-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200',
                    },
                    [h('span', { class: 'icon-[mingcute--right-line] text-gray-400 text-sm' })],
                  ),
                ],
              )
            }),
          ),
        ])
        : null

      return h('div', [
        thinkingElement,
        answerElement,
        sourceElement,
        // 知识来源抽屉
        h(
          Drawer,
          {
            title: '知识来源详情',
            placement: 'right',
            width: 500,
            open: sourceDrawerVisible.value,
            onClose: () => (sourceDrawerVisible.value = false),
            bodyStyle: { padding: '16px' },
          },
          {
            default: () =>
              h(
                List,
                {
                  dataSource: currentSources.value,
                  itemLayout: 'vertical',
                  size: 'large',
                },
                {
                  renderItem: ({ item, index }) =>
                    h(
                      List.Item,
                      {
                        key: index,
                        actions: [
                          h(
                            Button,
                            {
                              type: 'link',
                              icon: h(LinkOutlined),
                              onClick: () => {
                                // 如果有 URL 就打开，否则提示
                                if (item.url) {
                                  window.open(item.url, '_blank')
                                } else {
                                  console.log('暂无原文链接')
                                }
                              },
                            },
                            {
                              default: () => '查看原文',
                            },
                          ),
                        ],
                      },
                      {
                        default: () => [
                          h(List.Item.Meta, {
                            title: h('div', { class: 'flex items-center justify-between' }, [
                              h('span', { class: 'font-semibold' }, item.metadata.filename),
                              h(
                                Tag,
                                { color: 'green' },
                                {
                                  default: () => '文档',
                                },
                              ),
                            ]),
                            description: h('div', { class: 'space-y-2' }, [
                              h(
                                Paragraph,
                                {
                                  ellipsis: { rows: 4, expandable: true },
                                  class: 'text-gray-600 mb-2',
                                },
                                {
                                  default: () => item.content,
                                },
                              ),
                              h('div', { class: 'flex items-center text-xs text-gray-400' }, [
                                h(CalendarOutlined, { class: 'mr-1' }),
                                h('span', `来源文件: ${item.metadata.filename}`),
                              ]),
                            ]),
                          }),
                        ],
                      },
                    ),
                },
              ),
          },
        ),
      ])
    },
  },
  local: {
    placement: 'end',
    variant: 'filled',
  },
  file: {
    placement: 'end',
    variant: 'borderless',
    messageRender: (items) =>
      h(Flex, { vertical: true, gap: 'middle' }, () =>
        items.map((item) => h(Attachments.FileCard, { key: item.uid, item: item })),
      ),
  },
}

// 知识来源抽屉 - 优化样式
h(
  Drawer,
  {
    title: '参考来源详情',
    placement: 'right',
    width: 520,
    open: sourceDrawerVisible.value,
    onClose: () => (sourceDrawerVisible.value = false),
    bodyStyle: { padding: '0' },
    headerStyle: { borderBottom: '1px solid #f0f0f0' },
  },
  {
    default: () =>
      h('div', { class: 'h-full' }, [
        // 统计信息
        h('div', { class: 'px-6 py-4 bg-gray-50 border-b border-gray-200' }, [
          h(
            'div',
            { class: 'text-sm text-gray-600' },
            `共找到 ${currentSources.value.length} 条相关内容`,
          ),
        ]),
        // 来源列表
        h('div', { class: 'flex-1 overflow-y-auto' }, [
          h(
            List,
            {
              dataSource: currentSources.value,
              itemLayout: 'vertical',
              size: 'large',
              split: false,
            },
            {
              renderItem: ({ item, index }) =>
                h(
                  'div',
                  {
                    key: index,
                    class:
                      'px-6 py-4 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200',
                  },
                  [
                    // 文件头部信息
                    h('div', { class: 'flex items-center justify-between mb-3' }, [
                      h('div', { class: 'flex items-center' }, [
                        h(
                          'div',
                          {
                            class: `w-8 h-8 rounded ${getFileTypeInfo(item.metadata.filename).color} flex items-center justify-center mr-3`,
                          },
                          [
                            h('span', {
                              class: `${getFileTypeInfo(item.metadata.filename).icon} text-base`,
                            }),
                          ],
                        ),
                        h('div', [
                          h(
                            'div',
                            { class: 'font-medium text-gray-900 text-sm mb-1' },
                            item.metadata.filename,
                          ),
                          h('div', { class: 'text-xs text-gray-500' }, `文档片段 ${index + 1}`),
                        ]),
                      ]),
                      h(
                        Button,
                        {
                          type: 'text',
                          size: 'small',
                          icon: h(LinkOutlined),
                          onClick: () => {
                            if (item.url) {
                              window.open(item.url, '_blank')
                            } else {
                              console.log('暂无原文链接')
                            }
                          },
                          class: 'text-blue-600 hover:text-blue-700 hover:bg-blue-50',
                        },
                        {
                          default: () => '查看原文',
                        },
                      ),
                    ]),
                    // 内容预览
                    h(
                      'div',
                      {
                        class: 'bg-white rounded-lg border border-gray-200 p-4',
                      },
                      [
                        h(
                          'div',
                          {
                            class: 'text-sm text-gray-700 leading-relaxed line-clamp-6',
                          },
                          item.content,
                        ),
                      ],
                    ),
                  ],
                ),
            },
          ),
        ]),
      ]),
  },
)

// 获取文件类型信息
const getFileTypeInfo = (filename) => {
  const ext = filename.split('.').pop()?.toLowerCase() || ''
  const typeMap = {
    // PDF
    pdf: {
      icon: 'icon-[mdi--file-pdf-box]',
      color: 'bg-red-100 text-red-600',
      label: 'PDF',
    },
    // PPT
    ppt: {
      icon: 'icon-[mdi--file-powerpoint-box]',
      color: 'bg-orange-100 text-orange-600',
      label: 'PPT',
    },
    pptx: {
      icon: 'icon-[mdi--file-powerpoint-box]',
      color: 'bg-orange-100 text-orange-600',
      label: 'PPT',
    },
    // Word
    doc: {
      icon: 'icon-[mdi--file-word-box]',
      color: 'bg-blue-100 text-blue-600',
      label: 'DOC',
    },
    docx: {
      icon: 'icon-[mdi--file-word-box]',
      color: 'bg-blue-100 text-blue-600',
      label: 'DOC',
    },
    // Excel
    csv: {
      icon: 'icon-[mdi--file-excel-box]',
      color: 'bg-green-100 text-green-600',
      label: 'XLS',
    },
    xls: {
      icon: 'icon-[mdi--file-excel-box]',
      color: 'bg-green-100 text-green-600',
      label: 'XLS',
    },
    xlsx: {
      icon: 'icon-[mdi--file-excel-box]',
      color: 'bg-green-100 text-green-600',
      label: 'XLS',
    },
  }

  return (
    typeMap[ext] || {
      icon: 'icon-[mdi--file-document]',
      color: 'bg-gray-100 text-gray-600',
      label: ext?.toUpperCase() || 'DOC',
    }
  )
}


